package org.tiny.autounit.core.data.transport.server.codec;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.tiny.autounit.core.data.transport.server.domain.NettyMessage;

/**
 * @author shichaoyang
 * @Description: 编码器
 * @date 2019-01-30 11:24
 */
public class NettyMessageEncoder extends MessageToByteEncoder<NettyMessage> {

    @Override
    protected void encode(ChannelHandlerContext ctx, NettyMessage msg, ByteBuf out) throws Exception {
        byte[] data = SerializeUtil.serialize(msg);
        ByteBuf buf = Unpooled.copiedBuffer(intToBytes(data.length), data);
        out.writeBytes(buf);
    }

    /**
     * 在消息体头部附带4字节，主要是为了拆分消息用
     *
     * @param num
     * @return
     */
    public byte[] intToBytes(int num) {
        byte[] bytes = new byte[4];
        for (int i = 0; i < 4; i++) {
            bytes[i] = (byte) (num >> (24 - i * 8));
        }
        return bytes;
    }
}
